﻿using PublicCom;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UpdateApp
{
    public partial class ShowDoc : System.Web.UI.Page
    {
        private TempHelper temp = new TempHelper();

        //paraType=1 Get参数 paraType=2 Post参数 paraType=3 Json参数 paraType=4 Return参数 paraType=5 ReturnJson参数
        //paraType=6 json的键值对
        protected int isNotes = 0, isConvert = 0, isType = 1, isNum = 0;
        string cName = "", classNotes = "";
        //过滤的字段 不用，过滤后的字段列表的索引和类文件实际的索引不一致
        string noCols = "";
        Dictionary<string, string> list;
        protected string Content;

        protected void Page_Load(object sender, EventArgs e)
        {
            ReadFile obj = new ReadFile("/Template/ShowDoc.html");

            List<string> files = Session["FileList"] != null ? (List<string>)Session["FileList"] : new List<string>();

            if (files.Count == 0)
                return;

            isNotes = Convert.ToInt32(this.Notes.Checked);
            isNum = Convert.ToInt32(this.Num.Checked);

            list = ReadClassFile(files[0], 0);

            obj.Replace_PublicStr("host", this.host.Value);
            obj.Replace_PublicStr("classNotes", classNotes);
            obj.Replace_PublicStr("cName", cName);

            DataTable dt = temp.Convert(list);

            obj.OutList(dt, "key", "key", "list_class", 0, "index");

            int i = 1;
            //基础数据
            obj.Replace_PublicStr("getParams" + i, ParamCols(this.reqParams.Value, noCols, 1, 0));
            obj.Replace_PublicStr("baseParams" + i, ParamCols(this.baseParams.Value, noCols, 5, 0));
            obj.Replace_PublicStr("returnParams" + i, ParamCols(this.baseParams.Value, noCols, 4, 0));
            i++;

            //列表
            obj.Replace_PublicStr("jsonParams" + i, ParamCols(this.reqParams.Value, noCols, 6, 0));
            obj.Replace_PublicStr("postParams" + i, ParamCols(this.reqParams.Value, noCols, 2, 0));
            obj.Replace_PublicStr("listParams" + i, ParamCols(this.listParams.Value, noCols, 5, 0));
            obj.Replace_PublicStr("returnParams" + i, ParamCols(this.listParams.Value, noCols, 4, 0));
            i++;

            //详情
            obj.Replace_PublicStr("getParams" + i, ParamCols(this.reqParams.Value, noCols, 1, 0));
            obj.Replace_PublicStr("detailParams" + i, ParamCols(this.detailParams.Value, noCols, 5, 0));
            obj.Replace_PublicStr("returnParams" + i, ParamCols(this.detailParams.Value, noCols, 4, 0));
            i++;

            //保存
            obj.Replace_PublicStr("jsonParams" + i, ParamCols(this.reqParams.Value, noCols, 6, 0));
            obj.Replace_PublicStr("detailParams" + i, ParamCols(this.saveParams.Value, noCols, 5, 0));
            obj.Replace_PublicStr("postParams" + i, ParamCols(this.saveParams.Value, noCols, 2, 0));
            i++;

            Content = temp.ReadFile(obj);
        }

        public string ParamCols(string paramCols, string noCols, int paraType, int isNull)
        {
            string str = "";
            if (paramCols != "")
            {
                if (paraType == 1)
                {    //get参数
                    str = "?";
                    foreach (string i in paramCols.Split(','))
                    {
                        string c = ConvertClassCol(i);

                        if (c != null)
                        {
                            string[] cs = c.Split('|');
                            str += cs[0] + "=" + (isMarks(cs[1]) ? "1" : cs[cs.Length - 1]) + "&";
                        }
                    }

                    str = str == "?" ? "" : str;
                    str = str.EndsWith("&") ? str.Remove(str.Length - 1) : str;
                }
                else if (paraType == 2 || paraType == 4)
                {    //post&return 参数
                    foreach (string i in paramCols.Split(','))
                        str += Column(ConvertClassCol(i), noCols, paraType, isNull);
                }
                else if (paraType == 3 || paraType == 5)
                {   //post&return json参数
                    Dictionary<string, object> data = new Dictionary<string, object>();

                    foreach (string i in paramCols.Split(','))
                        ColumnJson(ConvertClassCol(i), noCols, paraType, data);

                    str = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                }
                else if (paraType == 6)
                {    //json的键值对
                    foreach (string i in paramCols.Split(','))
                    {
                        string c = ConvertClassCol(i);
                        if (c != null)
                        {
                            string[] cs = c.Split('|');
                            string cDesc = cs[cs.Length - 1] != "" ? cs[cs.Length - 1] : cName;
                            str += string.Format("\"{0}\": {1},", cs[0], (isMarks(c) && cs[1] != "DateTime" ? "1" : "\"" + cDesc + "\""));
                        }
                    }
                }
            }
            else
            {
                if (paraType == 4)
                {    //返回参数说明
                    foreach (string c in list.Keys)
                    {
                        str += Column(list[c], noCols, paraType, isNull);
                    }
                }
                else if (paraType == 5)
                {
                    Dictionary<string, object> data = new Dictionary<string, object>();

                    foreach (string c in list.Keys)
                        ColumnJson(list[c], noCols, paraType, data);

                    str = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                }
            }

            return str;
        }

        public string Column(string c, string noCols, int paraType, int isNull)
        {
            if (c == null)
                return "";

            string[] cs = c.Split('|');

            string cName = cs[0];
            string cType = cs[1];
            string cDesc = cs[cs.Length - 1] != "" ? cs[cs.Length - 1] : cName;

            if (isNum == 1 && !isMarks(cType))
                return "";

            if (paraType == 2)
            {
                return string.Format("<div>* @param {0} {1} {2} {3}</div>", cName, isNull == 1 ? "可选" : "必选", cType, cDesc);
            }
            else if (paraType == 4)
            {
                return string.Format("<div>* @return_param {0} {1} {2}</div>", cName, cType, cDesc);
            }

            return "";
        }

        public void ColumnJson(string c, string noCols, int paraType, Dictionary<string, object> data)
        {
            if (c == null)
                return;

            string[] cs = c.Split('|');

            string cName = cs[0];
            string cType = cs[1];
            string cDesc = cs[cs.Length - 1] != "" ? cs[cs.Length - 1] : cName;

            if (cType == "DateTime")
            {
                data.Add(cName, DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd")));
            }
            else if (isMarks(cType))
            {
                data.Add(cName, 1);
            }
            else
            {
                data.Add(cName, cDesc);
            }
        }

        public Dictionary<string, string> ReadClassFile(string filePath, int count)
        {
            Dictionary<string, string> list = new Dictionary<string, string>();
            string flag = "", required = "", type = "";

            try
            {
                FileStream file = null;
                StreamReader read = null;

                if (File.Exists(filePath))
                {
                    file = new FileStream(filePath, FileMode.Open);

                    read = new StreamReader(file);

                    string str = read.ReadLine();

                    while (str != null)
                    {
                        if (str.IndexOf("///") >= 0 && str.IndexOf("summary") < 0)
                        {
                            //当前注释
                            flag = Regex.Replace(str, @"\s", "").Replace("///", "");
                        }
                        //当前属性是否不能为空
                        else if (str.IndexOf("AllowNull") >= 0 || str.IndexOf("Exclude") >= 0 || count == 1)
                        {
                            required = "否";
                        }

                        //当该字符串为类名或属性名时
                        if (str.IndexOf("public") >= 0)
                        {
                            //当前行的代码集合		
                            List<string> temps = new List<string>();

                            if (str.IndexOf("{") > 0)
                                str = str.Split('{')[0];

                            //将当前行的代码按空格分隔成集合
                            foreach (string item in str.Split(' '))
                            {
                                if (item.Trim() == "")
                                    continue;

                                temps.Add(item.Trim());
                            }

                            //当前类名 寻找class后面的元素
                            if (str.IndexOf(" class ", StringComparison.CurrentCultureIgnoreCase) >= 0)
                                for (int i = 0; i < temps.Count; i++)
                                    if (temps[i].Equals("class", StringComparison.CurrentCultureIgnoreCase))
                                        cName = temps[i + 1].Replace("InfoEx", "").Replace("Info", "");

                            if (classNotes == "" || count > 0)
                            {
                                bool temp = false;
                                foreach (string item in temps)
                                {
                                    //为类名时，当count=0时 为第一个实体类，设置类名，其它情况不能设置
                                    if (item.ToLower() == "class")
                                    {
                                        if (count == 0)
                                            classNotes = flag != "" ? flag : " ";

                                        temp = true;

                                        break;
                                    }
                                }

                                if (temp)
                                {
                                    flag = "";
                                    required = "";

                                    //退出本次循环前要读取下一行，否则str一直不变，引起死循环
                                    str = read.ReadLine();
                                    continue;
                                }
                            }


                            if (isNotes == 1 && flag == "")
                            {
                                required = "";

                                str = read.ReadLine();
                                continue;
                            }

                            if (isConvert == 1)
                            {
                                switch (temps[1].Replace("?", "").ToLower())
                                {
                                    case "int":
                                    case "long":
                                    case "float":
                                    case "double":
                                        type = "number";
                                        break;
                                    case "datetime":
                                        type = "date";
                                        break;
                                    case "string":
                                        type = "string";
                                        break;
                                    case "list":
                                        type = "array";
                                        break;
                                    default:
                                        type = "object";
                                        break;
                                }
                            }
                            else
                            {
                                type = temps[1].Replace("?", "");
                            }

                            if (required == "")
                                required = temps[1].IndexOf("?") < 0 ? "是" : "否";

                            if (isType == 1)
                                list.Add(temps[temps.Count - 1], temps[temps.Count - 1] + "|" + type + "|" + required + "|" + flag);
                            else
                                list.Add(temps[temps.Count - 1], temps[temps.Count - 1] + "|" + type + "|" + flag);

                            flag = "";
                            required = "";
                        }

                        str = read.ReadLine();
                    }

                    file.Dispose();
                    read.Dispose();
                }
            }
            catch (Exception)
            {

            }

            //删除过滤的字段	
            foreach (string str in noCols.Split(','))
                list.Remove(str);

            return list;
        }

        public List<string> ToList(string cols)
        {
            List<string> list = new List<string>();

            foreach (string key in cols.Split('|'))
            {
                if (key == "" || key.StartsWith("\\"))
                    continue;

                list.Add(key);
            }

            return list;
        }

        //将列的索引转换列名
        public string ConvertClassCol(string value)
        {
            int index;
            if (int.TryParse(value, out index))
            {
                int i = 0;
                foreach (string key in list.Keys)
                {
                    if (i == index)
                        return list[key];

                    i++;
                }
            }
            else
            {
                foreach (string key in list.Keys)
                {
                    if (key.Equals(value, StringComparison.CurrentCultureIgnoreCase))
                        return list[key];
                }
            }

            return null;
        }

        //是否需要引号
        public bool isMarks(string c)
        {
            bool flag = false;

            switch (c)
            {
                case "int":
                case "bigint":
                case "long":
                case "decimal":
                case "double":
                case "DateTime":
                    flag = true;
                    break;
                default:
                    break;
            }

            return flag;
        }
    }
}